package com.robusta.cityuate.dialogs;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.robusta.cityuate.R;
import com.robusta.cityuate.objects.Country;
import com.robusta.cityuate.services.HTTPService;
import com.robusta.cityuate.utils.ConnectionUtils;

public class CountryPickerFragment extends SherlockDialogFragment implements
		TextWatcher {

	public interface CountryPickerCallback{
		public void setCountry(Country country);
	}
	

	private EditText countryField;
	// List view
	private ListView lv;
	private Context mContext = this.getActivity();
	private JSONArray countries;
	protected static final int CHOOSE_COUNTY_ACTIVITY = 2;
	protected static final String COUNTRY = "country";

	// Listview Adapter
	ArrayAdapter<Country> adapter;

	// Listview Data
	List<Country> countriesNames;

	// Search EditText
	EditText inputSearch;
	View empty;

	// ArrayList for Listview
	ArrayList<HashMap<String, String>> productList;
	private ProgressBar progressBar;
	private Button retryBtn;
	private View view;
	private int countryViewId;

	public static CountryPickerFragment getInstance(int viewId, Country country){
		
		
		CountryPickerFragment v=new CountryPickerFragment();

		Bundle b=new Bundle();
		b.putInt("com", viewId);
		v.setArguments(b);
		return v;
	}
	
	@Override
	public void onAttach(Activity activity) {
		mContext=activity;
		super.onAttach(activity);
	}
	
	@Override
	public void onActivityCreated(Bundle arg0) {
		super.onActivityCreated(arg0);
		mContext=getActivity();
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		countryViewId=getArguments().getInt("com");
		
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.country_picker, container);
		getDialog().setTitle(R.string.pick_counrty);
		countriesNames = new ArrayList<Country>();
		empty = view.findViewById(android.R.id.empty);

		// lv = (ListView) findViewById(R.id.list);
		lv = (ListView)view.findViewById(android.R.id.list);
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				//Log.d("onSlectItem", "here");
				//Intent result = new Intent();
				//result.putExtra(COUNTRY,
					//	((Country) arg0.getAdapter().getItem(position)));
				// setResult(RESULT_OK, result);
				// finish();
				Country chosen=((Country) arg0.getAdapter().getItem(position));
				countryField = (EditText) getActivity().findViewById(countryViewId);
				 countryField.setText(chosen.getName());
				((CountryPickerCallback)getActivity()).setCountry(chosen);
				 dismiss();
			}

		});
		//lv.setEmptyView(empty);
		inputSearch = (EditText) view.findViewById(R.id.inputSearch);
		progressBar = (ProgressBar) view.findViewById(R.id.loading);
	
		return view;
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);


		// Enabling Search Filter
		inputSearch.addTextChangedListener(this);

		// show retry button
		retryBtn = (Button) view.findViewById(R.id.btn_retry);
		retryBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				retryBtn.setVisibility(View.GONE);
				progressBar.setVisibility(View.VISIBLE);
				LoadFeedData loadFeedData = new LoadFeedData();
				loadFeedData.execute();
			}
		});

		LoadFeedData loadFeedData = new LoadFeedData();
		loadFeedData.execute();

	}

	private class LoadFeedData extends AsyncTask<Void, Void, List<String>> {

		private String URL = HTTPService.API_URL + "/countries";
		private DefaultHttpClient client;
		private HttpResponse response;

		private String responseString;

		@Override
		protected void onPostExecute(List<String> result) {
			progressBar.setVisibility(View.GONE);
			if (result != null) {
				Log.e("Asyn", "post excute");
				// adapter.notifyDataSetChanged();
				adapter = new ArrayAdapter<Country>(mContext,
						android.R.layout.simple_list_item_1, countriesNames);
				if(adapter!=null)
					adapter.getFilter().filter(inputSearch.getText().toString());
				lv.setAdapter(adapter);
				lv.setEmptyView(empty);
				inputSearch.setEnabled(true);
			}
			super.onPostExecute(result);
		}

		@Override
		protected List<String> doInBackground(Void... arg0) {
			HttpGet request = new HttpGet(URL);
			request.setHeader("Accept", "vnd.cityuate.v1");
			request.setHeader("Content-type", "application/json");
			Log.e("Asyn", "Before request");
			try {
				// getting response and filling the names list with it
				client = new DefaultHttpClient();
				response = client.execute(request);
				Log.e("Asyn", "response" + response);
				responseString = EntityUtils.toString(response.getEntity());
				countries = new JSONArray(responseString);

				Log.e("Asyn", "re" + countries.toString());
				countriesNames = new ArrayList<Country>();

				for (int i = 0; i < countries.length(); i++) {
					JSONObject c = countries.getJSONObject(i);
					countriesNames.add(Country.getCountryFromJSON(c));
				}
				return new ArrayList<String>();
			} catch (Exception e) {
				failScenario();

			}

			return null;

		}

		@Override
		protected void onPreExecute() {
			if (!ConnectionUtils.isNetworkAvailable(mContext)) {
				ConnectionUtils.showNoConnectionDialog(mContext);
				failScenario();
				cancel(true);

			} else
				progressBar.setVisibility(View.VISIBLE);
			super.onPreExecute();

		}

	}

	/**
	 * when fail to connect or get any data
	 */
	private void failScenario() {
		progressBar.setVisibility(View.GONE);
		retryBtn.setVisibility(View.VISIBLE);
	}

	@Override
	public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
		// When user changed the Text
		if(adapter!=null)
			adapter.getFilter().filter(cs);
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {

	}

	@Override
	public void afterTextChanged(Editable arg0) {
	}

}
